import axios from "axios"
import * as auth from '@/utils/auth.js'

export let downloadutil = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 100000
});

downloadutil.interceptors.request.use(config => {
    config.headers = {
      Authorization: auth.getToken(),
      // OrgId: auth.getUser().orgId,
      // UserId: auth.getUser().id,
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

let downloadFile = async (url, formData, options) => {
  await downloadutil.post(url, formData, {responseType: 'arraybuffer'}).then(resp => download(resp, options))
}

let getFile = async (url, options) => {
  await downloadutil.get(url, {responseType: 'blob'}).then(resp => download(resp, options))
}

let download = (resp, options) => {
  if (resp.data.type == "application/json") {
    //说明是普通对象数据，读取信息
    const fileReader = new FileReader();
    fileReader.onloadend = () => {
      var jsonData;
      try {
        jsonData = JSON.parse(fileReader.result);
      } catch (eror) {}
      // 读取后台信息
      if(jsonData){
        if (jsonData.code != "500") {
          createBlob(resp, options);
        } else {
          alert(jsonData.msg);
        }
      }else{
        createBlob(resp, options);
      }
    };
    fileReader.readAsText(resp.data);
  }else{
    createBlob(resp, options);
  }
}

function createBlob(resp, options) {
  let blob = new Blob([resp.data], {
    type: options.fileType ? options.fileType : "application/octet-binary",
  });
  //创建下载的链接
  let href = window.URL.createObjectURL(blob);
  downloadBlob(href, options.fileName);
}

let downloadBlob = (blobUrl, fileName, revokeObjectURL) => {
  let downloadElement = document.createElement('a')
  downloadElement.href = blobUrl
  //下载后文件名
  downloadElement.download = fileName
  document.body.appendChild(downloadElement)
  //点击下载
  downloadElement.click()
  //下载完成移除元素
  document.body.removeChild(downloadElement)
  if (revokeObjectURL == null || revokeObjectURL) {
    //释放掉blob对象
    window.URL.revokeObjectURL(blobUrl)
  }
}

let getDownloadFileUrl = async (url, fileType) => {
  let blob
  await downloadutil.get(url, {responseType: 'blob'}).then(resp => {
    blob = new Blob([resp.data], {type: fileType ? fileType : 'application/octet-binary'});
  })
  return window.URL.createObjectURL(blob);
}

let getDownloadFileUrlByPost = async (url, data, fileType) => {
  let blob
  await downloadutil.post(url, data, {responseType: 'blob'}).then(resp => {
    blob = new Blob([resp.data], {type: fileType ? fileType : 'application/octet-binary'});
  })
  return window.URL.createObjectURL(blob);
}

let getDownloadFileBlob = async (url, fileType) => {
  let blob
  await downloadutil.get(url, {responseType: 'blob'}).then(resp => {
    blob = new Blob([resp.data], {type: fileType ? fileType : 'application/octet-binary'});
  })
  return blob;
}

export default {
  downloadutil,
  downloadFile,
  getFile,
  getDownloadFileUrl,
  getDownloadFileUrlByPost,
  getDownloadFileBlob,
  downloadBlob
}
